package designpattern.adapter.springmvc;

import java.util.ArrayList;
import java.util.List;

public class DispatcherServlet {
    public List<HandlerAdapter> handlerAdapters = new ArrayList<>();

    public DispatcherServlet(){
        handlerAdapters.add(new HttpHandlerAdapter());
        handlerAdapters.add(new SimpleHandlerAdapter());
        handlerAdapters.add(new AnnotationHandlerAdapter());
    }

    public void doDispatcher(Controller controller){
        //得到能controller的适配器
        HandlerAdapter handlerAdapter = getHandler(controller);
        //执行controller里面的方法
        handlerAdapter.handle(controller);
    }

    public HandlerAdapter getHandler(Controller controller){
        //遍历handlerAdapters，寻找合适的适配器
        for(HandlerAdapter handlerAdapter:handlerAdapters){
            if(handlerAdapter.supports(controller)){
                return handlerAdapter;
            }
        }
        return null;
    }
}
